package com.aloha.boot03.controller;

import com.aloha.minio.service.MinioService;
import io.minio.BucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.lang.reflect.Field;

/**
 * @author zhdai
 * @date 2023/11/8 11:41
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Resource
    private MinioService minioService;

    @Resource
    private MinioClient minioClient;

    @PostMapping("/file")
    public void upload(@RequestPart("file") MultipartFile file) throws Exception {
        InputStream is = file.getInputStream();
        String bucket = "accident_data2";
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .bucket("bucket")
                    .object("001/111.jpg")
                    .stream(is, is.available(), -1)
                    .contentType(minioService.getContentType(file.getOriginalFilename())).build();
            changeBucket(BucketArgs.class.getDeclaredField("bucketName"), objectArgs, bucket);
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            throw new RuntimeException("file upload failed: " + e.getMessage());
        }
    }

    private void changeBucket(Field field, Object obj, String bucket) throws Exception {
        field.setAccessible(true);
        field.set(obj, bucket);
    }
}
